<?php

namespace app\middleware;

class Cors
{
    public function handle($request, \Closure $next)
    {
        // 设置CORS响应头
        header('Access-Control-Allow-Origin: *'); // 允许所有域名的跨域请求，为了安全起见，建议改为具体的域名
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); // 允许的HTTP方法
        header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization,author'); // 允许的HTTP头

        // 对于预检请求，特别是OPTIONS请求，直接返回状态码204
        if ($request->isOptions()) {
            return response('', 204);
        }

        return $next($request);
    }
}